﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Xaml;

namespace CivLib.CivIO
{
    /// <summary>
    /// This class contains a FlowDocument that CivLib can write to as it operates.
    /// This FlowDocument can be set as a System.Windows.Controls.RichTextBox.Document
    /// and that RichTextBox will display the messages.
    /// </summary>
    public static class CivConsole
    {
        private static FlowDocument m_consoleText = new FlowDocument(new Paragraph());
        /// <summary>
        /// Gets the FlowDocument that the console writes to
        /// </summary>
        public static FlowDocument ConsoleText { get { return m_consoleText; } }

        private static Paragraph m_currentBlock = (Paragraph)m_consoleText.Blocks.LastBlock;
        private static int m_linesPerBlock = 250;
        private static int m_maxBlocks = 250;
        private static int m_currentLine = 0;

        /// <summary>
        /// Adds the message with a newline appended to the console
        /// </summary>
        /// <param name="a_message">string witht the message</param>
        public static void Write(string a_message)
        {
            if (m_currentLine == 0)
                m_currentBlock.Inlines.Add(new Run(a_message));
            else if (m_currentLine > m_linesPerBlock)
            {
                if (m_consoleText.Blocks.Count > m_maxBlocks)
                    m_consoleText.Blocks.Remove(m_consoleText.Blocks.FirstBlock);
                m_consoleText.Blocks.Add(new Paragraph(new Run(a_message)));
                m_currentBlock = (Paragraph)m_consoleText.Blocks.LastBlock;
            }
            else
                m_currentBlock.Inlines.Add(new Run("\r\n" + a_message));

                m_currentLine++;
        }

        /// <summary>
        /// Clears the FlowDocument that represents the console
        /// </summary>
        public static void Clear()
        {
            m_consoleText.Blocks.Clear();
            m_consoleText.Blocks.Add(new Paragraph());
            m_currentBlock = (Paragraph)m_consoleText.Blocks.LastBlock;
            m_currentLine = 0;
        }
    }
}
